<template>
    <div  v-loading="loading" :element-loading-text="loadingText">
      <el-row :gutter="20">
        <el-col :span="16" class="infor_wrap">
          <el-transfer
            filterable
            filter-placeholder="Please Input Hourse Name"
            :titles="['PyhsicalRoom List', 'Selected PyhsicalRoom List']"
            v-model="transferValue"
            :data="transferData"
            @change="handleTransferChange">
          </el-transfer>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <!-- 批量价格设置 -->
              <span>Batch Price Setting</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="doReset">Reset</el-button>
            </div>
            <el-form ref="formData" :model="formData"  :rules="rules" label-width="125px">
              <el-form-item label="Date Range"  prop="dateRange">
                <div class="block" style="width: 100%">
                  <el-date-picker style="width: 70%"  class="input-size"
                                  v-model="formData.dateRange"
                                  type="daterange"
                                  align="right"
                                  unlink-panels
                                  range-separator="to"
                                  start-placeholder="Start Date"
                                  end-placeholder="End Date"
                                  :picker-options="pickerOptions"
                                  format="yyyy-MM-dd"
                                  value-format="yyyy-MM-dd">
                  </el-date-picker>
                </div>
              </el-form-item>

              <el-form-item label="Platform"  prop="platform" class="form-item-wd">
                <el-select v-model="formData.platform" placeholder="Please Select A Platform"  class="input-size">
                  <el-option :value="item.value" v-for="item in platforms">{{item.label}}</el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="Currency"  prop="currency" class="form-item-wd">
                <el-select v-model="formData.currency" placeholder="Please Select A Currency" class="input-size">
                  <el-option :value="currency"  v-for="(currency, index) in currencies">{{currency}}</el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="Rule Switch" required v-if="formData.switchFlag">
                <el-switch
                  v-model="formData.switchFlag"
                  active-text="Change price according to rules"
                  inactive-text="Simple price revision"
                >
                </el-switch>
              </el-form-item>

              <el-form-item label="Price Rules" required v-if="formData.switchFlag">
                <el-select v-model="formData.priceRule" placeholder="Please Select A Price Rules" style="width:90%;">
                  <el-option label="No" value="-1"></el-option><!--无-->
                  <el-option label="Not less than the following price" value="1"></el-option><!--不低于以下价格-->
                  <el-option label="Multiple" value="2"></el-option><!--倍数-->
                  <el-option label="Summation" value="3"></el-option><!--相加-->
                </el-select>
              </el-form-item>

              <el-form-item label="Rule Description" v-if="formData.switchFlag"><!-- 规则说明 -->
                <!-- 不低于以下价格：输入数字后将相应房源的对应日历低于该价格的日历上调至最低价格 -->
                <span style="color: red;font-size: 12px;" v-if="formData.priceRule==1">No less than the following price: after entering the number, increase the corresponding calendar of the corresponding house source to the lowest price</span>
                <!-- 倍数：浮点数，输入数字后，原来价格乘以该数字后成为新价格 -->
                <span style="color: red;font-size: 12px;"  v-else-if="formData.priceRule==2">Multiple: floating point number. After entering a number, the original price times the number to become a new price</span>
                <!-- 相加：浮点数，输入数字机后，原来价格增加该数字后成为新价格，可以为负数 -->
                <span style="color: red;font-size: 12px;"  v-else-if="formData.priceRule==3">Add: floating point number. After entering the digital machine, the original price increases to a new price, which can be a negative number</span>
                <!-- 无规则说明 -->
                <span style="color: red;font-size: 12px;" v-else>No rule description</span>
              </el-form-item>

              <el-form-item label="Price" prop="price"> <!-- 一键改价 -->
                <el-input v-model="formData.price"></el-input>
              </el-form-item>


              <el-form-item>
                <el-button type="primary" @click="doSave">Save Price</el-button>
              </el-form-item>

            </el-form>
          </el-card>

        </el-col>
      </el-row>
    </div>
</template>

<script>
  import config from '@/config';
  import {addModel,searchModel,searchModelByAsync,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
  import {getRoomEvents,insertOrder} from "@/api/event";
  import {getLidsByPid, getPidsByLid} from '@/api/room'

    export default {
        name: "BatchPriceSettingForm",
      data() {
        return {
          model: 'PriceCalendar', //
          bodyHeight:900,
          parentObj : null, //父对象
          loading:false,
          loadingText:'data load ...',
          currencies: null,
          platforms:null,
          transferValue:[],//已选中的穿梭框值
          transferData:[],//所有的穿梭框值
          dataCounter: this.getInitDataCounter(),/*数据更新计数器*/
          formData: this.getInitFormData(),
          rules: this.getInitRules(),
          pickerOptions: {
            shortcuts: [{
              text: 'Last week',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: 'Last month',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: 'Last three months',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }],
          }
        }
      },
      created() {
        const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
        // console.log("bodyHeight="+_bodyHeight);
        this.bodyHeight = _bodyHeight - 65;
        this.currencies = config.CURRENCY
        this.platforms = config.PLATFORM
      },
      mounted(){
        //this.loadDatas();
      },
      methods: {
          getInitDataCounter(){
            return {
              total:0,
              upCount:0,
              hasCount:0
            };
          },
        getInitFormData(respData){
          let _id = null;
          let _physical_room = this.roomId;
          let _platform = null;
          let _price = 0;
          let _currency = "JPY";
          let _date = null;
          let _dateRange = [];
          let _switchFlag = false; //规则改价开关 [true:按规则改价,false:简单改价]
          let _priceRule = -1;
          if(respData){
            _id = respData.id;
            _physical_room = respData.physical_room;
            _platform = respData.platform;
            _price = respData.price;
            _currency = respData.currency;
            _date = respData.date;
            _dateRange = respData.dateRange;
          }
          return  {
            id: _id,
            physical_room: _physical_room,
            platform:_platform,
            price:_price,
            currency:_currency,
            date: _date,
            dateRange:_dateRange,
            switchFlag:_switchFlag,
            priceRule:_priceRule //改价规则 [不低于以下价格,倍数,相加]
          };
        },
        getInitRules() {
          const _this = this;
          const custRulesCfg = this.getCustRulesConfig();
          const priceValid = custRulesCfg.floatValid('Price',1,100000);
          return {
            /*
            logical_room_id:[
              { required: true, message: 'Please Enter Logical_Room_Id', trigger: 'blur' },
              { min: 1, max: 100, message: '1 to 100 characters in length', trigger: 'blur' }
            ],*/
            dateRange:[
              { required: true, message: 'Please Select A Date range', trigger: 'change', type: 'array'}
            ],
            platform:[
              { required: true, message: 'Please Select A Platform', trigger: 'change'}
            ],
            currency:[
              { required: true, message: 'Please Select A Currency', trigger: 'change'}
            ],
            price:[
              { required: true,validator: priceValid,trigger: 'blur' }
            ]
          };
        },
        getCustRulesConfig(){
          return {
            intValid: function(label, min, max){
              const intValidFun = (rule, value, callback) => {
                if (!value) {
                  callback(new Error('Please Enter '+label));
                }
                try{
                  value = parseInt(value);
                }catch (e) {
                  callback(new Error(label+' Must be an integer value'));
                }

                if (!Number.isInteger(value)) {
                  callback(new Error(label+' Must be an integer value'));
                }
                if(min != null && max != null){
                  if(value < min || value > max){
                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                  }else{
                    callback();
                  }
                }
                if(min != null && max == null){
                  if (min && min > value) {
                    callback(new Error(label+' Must be greater than or equal to '+min));
                  } else {
                    callback();
                  }
                }

                if(max != null && min == null){
                  if (max && value > max) {
                    callback(new Error(label+' Must be less than or equal to '+max));
                  } else {
                    callback();
                  }
                }
              };
              return intValidFun;
            },
            floatValid: function(label, min, max,custCb){
              const intValidFun = (rule, value, callback) => {
                if (!value) {
                  callback(new Error('Please Enter '+label));
                }
                try{
                  value = parseFloat(value);
                }catch (e) {
                  callback(new Error(label+' Must be an float value'));
                }

                if (!Number.isInteger(value)) {
                  callback(new Error(label+' Must be an float value'));
                }
                if(min != null && max != null){
                  if(value < min || value > max){
                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                  }else{
                    if(custCb){
                      custCb(rule, value, callback);
                    }else{
                      callback();
                    }
                  }
                }
                if(min != null && max == null){
                  if (min && min > value) {
                    callback(new Error(label+' Must be greater than or equal to '+min));
                  } else {
                    callback();
                  }
                }

                if(max != null && min == null){
                  if (max && value > max) {
                    callback(new Error(label+' Must be less than or equal to '+max));
                  } else {
                    callback();
                  }
                }

              };
              return intValidFun;
            },
          };
        },
        refresh(_parentObj){
          console.log("refresh to do ...");
          this.parentObj = _parentObj;
          this.loadDatas();
        },
        /**
         * 加载数据
         */
        loadDatas(){
          console.log("loadDatas to do ...");
          const _this = this;
          this.doReset();
          _this.loadPhysicalRoomData();
        },
        loadPhysicalRoomData(){
          const _this = this;
          _this.loading = true;
          this.transferData = [];
          this.transferValue = [];
          searchModel('PhysicalRoom', {
            order_by: "-id",
            page: 1,
            page_size: 1000,
            //raw_filter: {},
            search_keys: {}
          }).then(res => {
            console.log("loadPhysicalRoomData.....");
            console.log(res);
            _this.loading = false;
            const list = res.data.list;
            this.convertDatas(list);
          });
        },
        convertDatas(list){
          this.transferData = list.map(item => {
            const _id = item.id;
            const _pid = item.physical_room_id;
            const _label = _pid+'|'+item.room_type+'|'+item.standard_price+item.standard_currency;
            return {key:_id, label:_label, pid: _pid};
          });
        },
        handleTransferChange(value, direction, movedKeys){
          console.log(value, direction, movedKeys);
        },
        /**
         * 保存数据
         */
        doSave(){
          console.log("doSave to do ...");
          const _this = this;
          let _formData = this.formData;
          for(var key in _formData){
            const val = _formData[key];
            if(!val && (val !== 0 || val !== '0')){
              delete _formData[key];
            }
          }
         if(!this.transferValue){
             _this.$message.error('Please Select Physical Room Listing!');
             return;
         }
          this.$refs['formData'].validate((valid) => {
            if (valid) {
              const _dateRange = _formData.dateRange;
              const _firstDate = _dateRange[0];
              const _lastDate = _dateRange[1];
              const firstDate =  moment(_firstDate).format('YYYY-MM-DD');
              let lastDate = moment(_lastDate).add(1, 'd');
              lastDate = moment(lastDate).format('YYYY-MM-DD');

              this.dataCounter = this.getInitDataCounter();
              this.dataCounter.total = this.transferValue.length;
              this.loading = true;
              const _pars = {platform:_formData.platform};
              searchModel('PriceCalendar', {
                  order_by: "-id",
                  page_size: 1000,
                  search_keys: _pars,
                  raw_filter: {
                      physical_room__in: this.transferValue,
                      date__gte: firstDate,
                      date__lt: lastDate
                  },
              }).then(res => {
                  _this.loading = false;
                  const list = res.data.list;
                  _this.saveBatchDatas(list);
              }).catch(err => {
                  _this.loading = false;
                  console.error(err);
              });

            } else {
              console.log('error submit!!');
              _this.$message.error('Please Check Input Form Data Has Errors!');
              return false;
            }
          });
        },
        /**
         * 批量保存数据
         * */
        saveBatchDatas(list){
          const dateArr = this.getDateArr();
          let dataArr = [];
          const _platform = this.formData.platform;
          const _price = this.formData.price;
          const _currency = this.formData.currency;
          this.transferValue.forEach(_physical_room_id => {
              const _dataArr = dateArr.map(_date => {
                    return {physical_room:_physical_room_id, platform:_platform, price:_price, currency:_currency, date:_date};
              });
              dataArr = dataArr.concat(_dataArr);
          });


          let methodArr = [];
          if((!list || list.length == 0) && dataArr.length > 0){
              const batchInsertPromise = this.batchInserts(dataArr);
              methodArr.push(batchInsertPromise);
          }else{
              list.forEach(item => {
                 const _date = item.date;
                 const _physical_room = item.physical_room;
                 item.platform = _platform;
                 item.price = _price;
                 item.currency = _currency;
                 let index = -1;
                 for(let i=0, count=dataArr.length; i<count; i++){
                    const _data = dataArr[i];
                    if(_physical_room == _data.physical_room && _date == _data.date){
                        index = i;
                        break;
                    }
                 }
                 if(index != -1) dataArr.splice(index, 1);
              });

              if(dataArr && dataArr.length > 0){
                  const batchInsertPromise = this.batchInserts(dataArr);
                  methodArr.push(batchInsertPromise);
              }
              if(list && list.length > 0){
                  const batchUpdatePromise =  this.batchUpdates(list);
                  methodArr.push(batchUpdatePromise);
              }

          }
          this.saveByParallel(methodArr);
        },
        saveByParallel(methodArr){
            if(!methodArr || methodArr.length == 0) return;
            this.loading = true;
            Promise.all(methodArr).then((res) => {
                this.loading = false;
                console.log(" Promise.all.success ... ");
                console.log(res);
                this.doReset();
                this.reloadParentData();
            }).catch(err => {
                console.error("======== 保存改价记录失败 =======");
                console.error(err);
            });
        },
        getDateArr(){
            const _formData = this.formData;
            const _dateRange = _formData["dateRange"];
            const _firstDate = _dateRange[0];
            const _lastDate = _dateRange[1];
            const days = this.getDays(_firstDate,_lastDate);
            const dateArr = [
                moment(_firstDate).format('YYYY-MM-DD')
            ];
            for(let i=1; i<=days; i++){
                let date = moment(_firstDate).add(i, 'd');
                date = moment(date).format('YYYY-MM-DD')
                dateArr.push(date);
            }
            return dateArr;
        },
        /**
         * 批量插入
         */
        batchInserts(dataArr){
            const _this = this;
            return new Promise((resolve, reject) => {
                addModels(_this.model, dataArr).then(res => {
                    this.loading = false;
                    resolve(res);
                    console.log("batchInserts.success ...");
                    console.log(res);
                }).catch(err =>{
                    this.loading = false;
                    console.log("batchInserts.failure ...");
                    console.error(err);
                    reject(err);
                });
            });
        },
        batchUpdates(dataArr){
            const _this = this;
            return new Promise((resolve, reject) => {
                updateModels(_this.model, dataArr).then(res => {
                    resolve(res);
                    console.log("batchUpdate.success ...");
                    console.log(res);
                }).catch(err =>{
                    console.log("batchUpdate.failure ...");
                    console.error(err);
                    reject(err);
                });
            });
        },
        /**
         *  获取截止日期和起始日期之间的天数
         * */
        getDays(startDate, endDate){
          const days = moment(endDate).diff(moment(startDate), 'days')
          //console.log(endDate+" - "+startDate+ "="+ days);
          return days;
        },
        reloadParentData(){
          const _this = this;
          _this.parentObj.loadOrderData();
        },
        getParent(){
          return this.parentObj ||  this.$parent;
        },
        /**
         * 重置表单
         */
        doReset(){
          this.formData = this.getInitFormData();
          this.loading = false;
          this.transferValue = [];
          if(this.$refs['formData']) this.$refs['formData'].resetFields();
        }
      }
    }
</script>

<style lang="less" scoped>

  .infor_wrap{
    height: calc(100% - 84px);
  /deep/ .el-transfer{
    height: calc(100% - 100px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  /deep/ .el-transfer-panel{
    width:320px;
    height: 650px;
  }
  /deep/ .el-transfer-panel__body{
    height: calc(100% - 40px);
  }
  /deep/ .el-transfer-panel__filter{
    margin: 0 15px;
  }
  /deep/ .el-transfer-panel .el-transfer-panel__header{
    margin-bottom: 10px;
  }
  /deep/ .el-transfer-panel__list.is-filterable{
    margin-top: 10px;
    height: calc(100% - 76px);
  }
  }
</style>
